package com.sdcqjy.property.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sdcqjy.mylibrary.IntentUtils;
import com.sdcqjy.mylibrary.OtherUtils;
import com.sdcqjy.mylibrary.ScreenUtils;
import com.sdcqjy.mylibrary.widget.PublicDialog;
import com.sdcqjy.mylibrary.widget.ShowToast;
import com.sdcqjy.mylibrary.widget.flyindicaor.FlycoPageIndicaor;
import com.sdcqjy.property.AppLL;
import com.sdcqjy.property.MyConstants;
import com.sdcqjy.property.R;
import com.sdcqjy.property.base.BaseFragment;
import com.sdcqjy.property.base.SimpleBaseActivity;
import com.sdcqjy.property.home.adapter.HomeContentAdapter;
import com.sdcqjy.property.home.fragment.ChanQuanFragment;
import com.sdcqjy.property.home.fragment.ShiWuFragment;
import com.sdcqjy.property.home.fragment.ZiChanFragment;
import com.sdcqjy.property.lawRegulations.LawRegulationsActivity;
import com.sdcqjy.property.mode.AppLev;
import com.sdcqjy.property.mode.CityMode;
import com.sdcqjy.property.mode.ImageMode;
import com.sdcqjy.property.mode.ListMsgMode;
import com.sdcqjy.property.mode.LoginMode;
import com.sdcqjy.property.presenter.MainPresenter;
import com.sdcqjy.property.presenter.contract.MainContract;
import com.sdcqjy.property.utils.GlideBannerImageLoader;
import com.sdcqjy.property.utils.GlideCircleTransform;
import com.sdcqjy.property.widget.AppDownloadDialog;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

import static com.sdcqjy.property.MyConstants.ChangeDataType;

/**
 * Created by 磁磁帅 on 2018/3/29.
 * 功能：
 */
public class MainActivity extends SimpleBaseActivity<MainPresenter> implements MainContract.View, OnRefreshListener {
    @BindView(R.id.mBanner)
    Banner mBanner;
    @BindView(R.id.mContentViewPager)
    ViewPager mContentViewPager;
    @BindView(R.id.textGuquan)
    TextView textGuquan;
    @BindView(R.id.textZhengzhi)
    TextView textZhengzhi;
    @BindView(R.id.textShiwuzican)
    TextView textShiwuzican;
    @BindView(R.id.textWangluojinjia)
    TextView textWangluojinjia;
    @BindView(R.id.icon)
    ImageView icon;
    @BindView(R.id.textCity)
    TextView textCity;
    @BindView(R.id.textReadNumb)
    TextView textReadNumb;
    @BindView(R.id.iconCity)
    ImageView iconCity;
    @BindView(R.id.textMsg)
    View textMsg;
    @BindView(R.id.textNameCity)
    TextView textNameCity;
    @BindView(R.id.indicator)
    FlycoPageIndicaor circleIndicator;
    @BindView(R.id.iconCity2)
    ImageView iconCity2;
    @BindView(R.id.textNameCity2)
    TextView textNameCity2;
    @BindView(R.id.mFlhbTextView)
    TextView mFlhbTextView;
    @BindView(R.id.smartLayout)
    SmartRefreshLayout smartLayout;
    private List<ImageMode> modeList;
    private HomeContentAdapter adapter;
    private BaseFragment fragments[];
    private boolean cityRef = false;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (MyConstants.ActionCityRef.equals(action)) {
                cityRef = true;
                if (fragments != null) {
                    for (int i = 0; i < fragments.length; i++) {
                        fragments[i].sendMessage(ChangeDataType, null);
                    }
                }
            } else if (MyConstants.ActionCityRef.equals(action)) {
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        setTranslucentStatus(true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        presenter = new MainPresenter(this);

        initBanner();
        initViewPager();

        smartLayout.setOnRefreshListener(this);

        IntentFilter filter = new IntentFilter(MyConstants.ActionCityRef);
        //filter.addAction(MyConstants.ActionLogin);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
    }

    private void initBanner() {
        modeList = new ArrayList<>();
        mBanner.isAutoPlay(true);
        mBanner.setImages(modeList);
        mBanner.setOnBannerListener(new OnBannerListener() {
            public void OnBannerClick(int i) {
                ImageMode imageMode = modeList.get(i);
                presenter.getDetailsMode(imageMode.documentID);
            }
        });
        mBanner.setImageLoader(new GlideBannerImageLoader());
        //设置轮播时间
        mBanner.setDelayTime(30000);
        //设置指示器位置（当banner模式中有指示器时）
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        mBanner.start();
    }

    private void initViewPager() {
        fragments = new BaseFragment[]{new ChanQuanFragment(), new ZiChanFragment(), new ShiWuFragment()};
        adapter = new HomeContentAdapter(getSupportFragmentManager(), fragments);
        mContentViewPager.setAdapter(adapter);
        mContentViewPager.setOffscreenPageLimit(3);
        circleIndicator.setViewPager(mContentViewPager);
    }

    protected void asynRun() {
        ViewGroup.LayoutParams params = mBanner.getLayoutParams();
        if (params != null) {
            int screenWidth = ScreenUtils.getScreenWidth(getActivity());
            params.height = screenWidth / 2;// * 2 / 5;
        }
        mFlhbTextView.postDelayed(this::setViewPagerH, 10);
        showDataOfCity();
        presenter.checkVersion();
    }

    private void setViewPagerH() {
//        int height = mFlhbTextView.getHeight();
//        if (height == 0) {
//            mFlhbTextView.postDelayed(this::setViewPagerH, 10);
//        } else {
        ViewGroup.LayoutParams params = mContentViewPager.getLayoutParams();
        if (params != null) {
            int screenHeight = ScreenUtils.getScreenHeight(getActivity())
                    - ScreenUtils.getStatusHeight(getActivity());
            int[] viewXY = OtherUtils.getViewXY(mContentViewPager);
            screenHeight = screenHeight - viewXY[1];
            params.height = screenHeight;
        }
//        }
    }

    protected void onResume() {
        super.onResume();
        if (cityRef) showDataOfCity();
        if (isLogin(false)) showDataOfLogin();
        else {
            textReadNumb.setVisibility(View.GONE);
            icon.setImageResource(R.mipmap.account_1);
        }
        hintInstall();
    }

    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
    }

    private String cqjyzxjyxm, yewuzhinan;

    public void onRefresh(RefreshLayout refreshlayout) {
        presenter.getImageList();
        presenter.getNoRead();
        for (int i = 0; i < fragments.length; i++) {
            BaseFragment fragment = fragments[i];
            fragment.sendMessage(1, null);
        }
        refreshlayout.finishRefresh(1000);
    }

    public void showDataOfCity() {
        presenter.getImageList();
        cityRef = false;
        CityMode mode = CityMode.getMode(getActivity());
        textCity.setText(mode.name + " >");

        Resources res = getResources();
        if (TextUtils.isEmpty(cqjyzxjyxm)) cqjyzxjyxm = res.getString(R.string.cqjyzxjyxm);
        if (TextUtils.isEmpty(yewuzhinan)) yewuzhinan = res.getString(R.string.yewuzhinan);
        //iconCity.setImageResource(mode.getLocaIcon());
        Typeface typefaceDiy = AppLL.typefaceDiy;
        textNameCity.setTypeface(typefaceDiy);
        textNameCity2.setTypeface(typefaceDiy);
        textNameCity.setText(/*mode.name +*/ cqjyzxjyxm);
        textNameCity2.setText(/*mode.name +*/ yewuzhinan);
    }

    private void showDataOfLogin() {
        LoginMode mode = LoginMode.getMode(getActivity());
        if (!TextUtils.isEmpty(mode.headImageUrl)) {
            Glide.with(getActivity()).
                    load(mode.headImageUrl).
                    transform(new GlideCircleTransform(getActivity())).
                    //asBitmap(). //强制处理为bitmap
                            error(R.mipmap.account_1).//加载失败时显示的图片
                    diskCacheStrategy(DiskCacheStrategy.RESULT).//保存最终图片
                    into(icon);//显示到目标View中
        } else {
            icon.setImageResource(R.mipmap.account_1);
        }
        textReadNumb.setVisibility(View.GONE);
        presenter.getNoRead();
    }

    @OnClick(R.id.icon)
    public void onIconClicked() {
        if (isLogin()) MyZoneActivity.open(getActivity());
    }

    @OnClick(R.id.textCity)
    public void onTextCityClicked() {
        SelectCityActivity.open(getActivity());
    }

    @OnClick(R.id.textSearch)
    public void onTextSearchClicked() {
        SearchActivity.open(getActivity());
    }

    @OnClick(R.id.imgHelp)
    public void onImgHelpClicked() {
        presenter.openDetailsOfListOne(8);
        //CategoryListActivity.open(getActivity(), 8);
    }

    @OnClick(R.id.textGuquan)
    public void onTextGuquanClicked() {
        CategoryListActivity.open(getActivity(), 9);
        //ListMsgActivity.open(this, 0);
    }

    @OnClick(R.id.textZhengzhi)
    public void onTextZhengzhiClicked() {
        CategoryListActivity.open(getActivity(), 10);
        //ListMsgActivity.open(this, 1);
    }

    @OnClick(R.id.textMsg)
    public void onTextMsgClicked() {
        if (isLogin()) MessageActivity.open(getActivity());
    }

    @OnClick(R.id.textShiwuzican)
    public void onTextShiwuzicanClicked() {
        CategoryListActivity.open(getActivity(), 11);
        //ListMsgActivity.open(this, 2);
    }

    @OnClick(R.id.textWangluojinjia)
    public void onTextWangluojinjiaClicked() {
        CategoryListActivity.open(this, 6);
        //ListMsgActivity.open(this, 3);
    }

    @OnClick(R.id.textTab1)
    public void onTextTab1Clicked() {
        mContentViewPager.setCurrentItem(0);
    }

    @OnClick(R.id.textTab2)
    public void onTextTab2Clicked() {
        mContentViewPager.setCurrentItem(1);
    }

    @OnClick(R.id.textTab3)
    public void onTextTab3Clicked() {
        mContentViewPager.setCurrentItem(2);
    }

    @OnClick(R.id.mFlhbTextView)
    public void onMFlhbTextViewClicked() {
        LawRegulationsActivity.open(getActivity());
        //presenter.getDetailsMode("25");
        //presenter.openDetailsOfListOne(25);
        //AssetsWordActivity.open(getActivity(), "法律法规最终版v2.pdf");
        //WebViewActivity.open(getActivity(), "法律汇编", a.Law);
    }

    @OnClick(R.id.mJdalTextView)
    public void onMJdalTextViewClicked() {
        SutraCaseActivity.open(getActivity());
    }

    @OnClick(R.id.mAboutTextView)
    public void onMAboutTextViewClicked() {
        AboutActivity.open(getActivity());
    }

    @OnClick(R.id.textMyZone)
    public void onTextMyZoneViewClicked() {
        if (isLogin()) MyZoneActivity.open(getActivity());
    }

    public void getImageListRet(List<ImageMode> data) {
        mBanner.update(data);
    }

    public void getDetailsModeRet(ListMsgMode data) {
        if (data.categoryID == 25) {
            WebViewActivity.open(getActivity(), getString(R.string.falvhuibian), data.htmlPath);
        } else DetailsActivity.open(getActivity(), data);
    }

    public void getNoReadRet(Integer data) {
        int value = data;
        if (value <= 0)
            textReadNumb.setVisibility(View.GONE);
        else {
            textReadNumb.setVisibility(View.VISIBLE);
            if (value > 99)
                textReadNumb.setText("99+");
            else
                textReadNumb.setText("" + value);
        }
    }

    private long oldTime;

    public void onBackPressed() {
        long time = System.currentTimeMillis();
        if (time - oldTime > 2000) {
            ShowToast.alertShortOfWhite(getActivity(), R.string.zayctc);
            oldTime = time;
        } else {
            super.onBackPressed();
        }
    }

    //-------------------------------------版本更新-------------------------------------
    private PublicDialog checkVersionDialog;
    private AppDownloadDialog downloadDialog;
    private AppDownloadDialog.OnDownloadListener onDownloadListener;
    private AlertDialog.Builder hintInstallDiaLog;
    private AppLev appLev;

    public void checkVersionRet(AppLev data) {
        //对比版本号
        if (data == null || TextUtils.isEmpty(data.version)) return;
        AppLev.setMode(getActivity(), data);
        String appVerName = OtherUtils.getAppVerName(this);
        if (!data.version.equals(appVerName)) {//提示更新
            String xinbanben = getResources().getString(R.string.xinbanben);
            String genxin = getResources().getString(R.string.genxin);
            if (checkVersionDialog != null) checkVersionDialog.dismiss();
            checkVersionDialog = new PublicDialog(this)
                    .setContent(data.content)
                    .setTitle(xinbanben + data.version)
                    .setConfirmBtnText(genxin)
                    .setOnPublicDialogClick(new PublicDialog.OnPublicDialogClick() {
                        public void onConfirmClick() {
                            MainActivity.this.appLev = AppLev.getMode(MainActivity.this);
                            checkSDCardPermission();
                        }

                        public void onCancelClick() {
                        }
                    });
            checkVersionDialog.show();
        }
    }

    private void checkSDCardPermission() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            downloadApp();
        } else {
            PermissionGen.with(MainActivity.this)
                    .addRequestCode(200)
                    .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .request();
        }
    }

    @PermissionSuccess(requestCode = 200)
    public void doSDLoadSuccess() {
        downloadApp();
    }

    @PermissionFail(requestCode = 200)
    public void doSDLoadFail() {
        new AlertDialog.Builder(MainActivity.this)
                .setOnKeyListener(onKeyListener)
                .setTitle(R.string.tishi)
                .setMessage(R.string.xzappxyqx_qkq)
                .setPositiveButton(R.string.shoudongkaiqi, (dialog, which) -> IntentUtils.goAppSetting(MainActivity.this))
                .setNegativeButton(R.string.changshishenqing, (dialog, which) -> checkSDCardPermission())
                .show();
    }

    public void downloadApp() {
        if (appLev != null) {
            //查看缓存
            AppLev mode = AppLev.getMode(this);
            if (mode != null) {
                if (mode.equVersion(appLev.version)) {
                    File installApk = mode.getInstallApk();
                    if (installApk != null && installApk.exists()) {
                        //认为下载完成，直接安装
                        upDataAppSucc(installApk);
                        return;
                    }
                }
                AppLev.clear(this);
            }
            presenter.upDataApp(appLev.getUrl());
            if (downloadDialog != null) downloadDialog.dismiss();
            downloadDialog = new AppDownloadDialog(getActivity()).setOnDownloadDialogSet(onDownloadListener ->
                    MainActivity.this.onDownloadListener = onDownloadListener);
            downloadDialog.show();
        }
    }

    public void upDataAppSucc(File file) {
        if (downloadDialog != null) {
            downloadDialog.dismiss();
            downloadDialog = null;
        }
        //进行缓存
        if (appLev != null) {
            appLev.setInstallApk(file);
            AppLev.setMode(this, appLev);
        }
        IntentUtils.goInstallApk(this, file);
    }

    public void upDataAppErr() {
        if (downloadDialog != null) {
            downloadDialog.dismiss();
            downloadDialog = null;
        }
        new AlertDialog.Builder(MainActivity.this)
                .setOnKeyListener(onKeyListener)
                .setTitle(R.string.tishi)
                .setMessage(R.string.yyxzsb)
                .setPositiveButton(R.string.zaicichangshi, (dialog, which) -> downloadApp())
                .setNegativeButton(R.string.quxiao, null)
                .show();
    }

    public void upDataAppProgress(long progress, long total) {//注：每2k返回一次，应乘以200
        if (onDownloadListener != null) onDownloadListener.onDownloadListener(progress, total);
    }

    // 提示安装
    private void hintInstall() {
        if (hintInstallDiaLog != null) return;
        if (appLev == null) return;
        File installApk = appLev.getInstallApk();
        if (installApk == null || !installApk.exists()) return;
        hintInstallDiaLog = new AlertDialog.Builder(MainActivity.this)
                .setOnKeyListener(onKeyListener)
                .setTitle(R.string.tishi)
                .setMessage(R.string.yyxzwc_xzaz)
                .setPositiveButton(R.string.anzhuang, (dialog, which) -> {
                    hintInstallDiaLog = null;
                    if (appLev != null && appLev.getInstallApk() != null)
                        upDataAppSucc(appLev.getInstallApk());
                })
                .setNegativeButton(R.string.quxiao, (dialog, which) -> {
                    hintInstallDiaLog = null;
                    appLev = null;
                });
        hintInstallDiaLog.show();
    }
    //-------------------------------------版本更新-------------------------------------

    //用于拦截按键监听
    private DialogInterface.OnKeyListener onKeyListener = (dialog, keyCode, event) -> true;
}
